package middleware

import (
	"net/http"
	"log"
	"gitee.com/Cookie_XiaoD/go-filestore-server/handlers"
	"strings"
)

//TokenMiddleware Token验证中间件
type TokenMiddleware struct {
	next http.Handler
	noAuthPath []string
}

func (tokenM *TokenMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	//判断当前请求是否是无需token验证的请求
	if tokenM.noAuthPath!=nil{
		for _,v:=range tokenM.noAuthPath{
			if strings.Index(r.URL.Path, v)!=-1{
				tokenM.next.ServeHTTP(w, r)
				return
			}
		}
	}


	token:=r.Header.Get("X-Token")
	if token==""{
		r.ParseForm()
		token=r.Form.Get("token")
	}

	if token==""{
		log.Println("请求头或请求字符串不包含token")
		w.WriteHeader(http.StatusUnauthorized)
		return
	}
	log.Printf("token信息：%v",token)
	pass:=handlers.IsTokenValid(token)
	if !pass{
		w.WriteHeader(http.StatusUnauthorized)
		return
	}

	tokenM.next.ServeHTTP(w, r)
}

func NewTokenMiddleware(handler http.Handler,noAuthPath []string)*TokenMiddleware{
	return &TokenMiddleware{next:handler,noAuthPath:noAuthPath}
}




